using System.Threading;

namespace eLoop;

class SingleUnsyncThreadScheduler : ASingleScheduler
{
    private static int index = 0;

    public SingleUnsyncThreadScheduler()
    {
        this.thread = new Thread(() =>
        {
            this.Loop();
        });

        this.thread.IsBackground = true;
        Interlocked.Increment(ref index);

        this.thread.Name = $"work_thread_{index}";

        this.Id = $"thread:{index}";
        this.Name = this.thread.Name;
        this.ThreadId = this.thread.ManagedThreadId;

        this.thread.Start();
    }

    private Thread thread;
    private AutoResetEvent semaphore = new AutoResetEvent(false);
    
    protected override void ExecuteLoop()
    {
        this.semaphore.Set();
    }

    private void Loop()
    {
        while (!this.IsDisposed)
        {
            if (base.IsEmpty())
            {
                this.semaphore.WaitOne();
            }

            base.DeliverWorks();
        }
    }

    public override void Dispose()
    {
        if (this.IsDisposed)
        {
            return;
        }

        this.Reset();
    }

    protected void Reset()
    {
        base.Dispose();
        
        this.semaphore.Set();

        this.semaphore.Dispose();
    }
}
